#!/bin/bash

# Windows AMD64 客户端打包脚本
# 用于将Flutter客户端打包成Windows AMD64版本

set -e

# 清理函数 - 现在TCP优化器文件已被移除，无需恢复
cleanup() {
    echo "清理完成"
}

# 注册退出时的清理
trap cleanup EXIT

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🪟 Windows AMD64 客户端打包脚本"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# 获取脚本所在目录
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$SCRIPT_DIR"

# 检查环境
echo "📋 检查构建环境..."
echo ""

# 检查Flutter
if ! command -v flutter &> /dev/null; then
    echo "❌ Flutter未安装或不在PATH中"
    echo "   请先安装Flutter: https://flutter.dev/docs/get-started/install"
    exit 1
fi

echo "✅ Flutter版本:"
flutter --version | head -n 1
echo ""

# 检查Go
if ! command -v go &> /dev/null; then
    echo "❌ Go未安装或不在PATH中"
    echo "   请先安装Go: https://golang.org/dl/"
    exit 1
fi

echo "✅ Go版本: $(go version)"
echo ""

# 检查当前操作系统
CURRENT_OS=$(uname -s)
echo "📟 当前操作系统: $CURRENT_OS"
echo ""

# ============================================================
# 步骤 1: 编译 Go Tunnel 库 (Windows AMD64)
# ============================================================

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🔨 步骤 1/3: 编译 Go Tunnel 库 (Windows AMD64)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

cd go_tunnel

# 清理 Go 构建缓存和临时文件
echo "🗑️  清理 Go 构建缓存和临时文件..."
go clean -cache 2>/dev/null || true
rm -f *.o *.a *.so *.dll *.dylib 2>/dev/null || true
echo ""

# TCP优化器文件已被移除，无需临时隐藏
echo "📦 准备Windows专用源文件..."
echo "TCP优化器文件已从项目中移除（QUIC架构不再需要）"
echo ""

# 创建输出目录
OUTPUT_DIR="../assets/libs"
mkdir -p "$OUTPUT_DIR"

OUTPUT_FILE="$OUTPUT_DIR/simple_tunnel_windows_amd64.dll"

# 清理旧文件
if [[ -f "$OUTPUT_FILE" ]]; then
    echo "🗑️  清理旧的DLL文件..."
    rm -f "$OUTPUT_FILE"
    rm -f "${OUTPUT_FILE%.*}.h"
fi

# 根据操作系统选择编译方式
if [[ "$CURRENT_OS" == "MINGW"* ]] || [[ "$CURRENT_OS" == "MSYS"* ]] || [[ "$CURRENT_OS" == "CYGWIN"* ]]; then
    # 在Windows上直接编译
    echo "✅ 检测到Windows系统，直接编译..."
    echo ""
    
    export GOOS=windows
    export GOARCH=amd64
    export CGO_ENABLED=1
    
    echo "🔍 构建参数: GOOS=$GOOS GOARCH=$GOARCH CGO_ENABLED=$CGO_ENABLED"
    echo ""
    
    if GOOS=windows GOARCH=amd64 CGO_ENABLED=1 go build -a -buildmode=c-shared -ldflags="-s -w" -o "$OUTPUT_FILE" *.go; then
        echo ""
        echo "✅ Windows DLL编译成功!"
        FILE_SIZE=$(ls -lh "$OUTPUT_FILE" | awk '{print $5}')
        echo "   文件: $OUTPUT_FILE"
        echo "   大小: $FILE_SIZE"
    else
        echo ""
        echo "❌ Windows DLL编译失败"
        exit 1
    fi
    
elif command -v x86_64-w64-mingw32-gcc &> /dev/null; then
    # 使用MinGW交叉编译
    echo "✅ 检测到MinGW工具链，使用交叉编译..."
    echo ""
    
    export GOOS=windows
    export GOARCH=amd64
    export CGO_ENABLED=1
    export CC=x86_64-w64-mingw32-gcc
    export CXX=x86_64-w64-mingw32-g++
    
    echo "🔍 构建参数: GOOS=$GOOS GOARCH=$GOARCH CGO_ENABLED=$CGO_ENABLED CC=$CC"
    echo ""
    
    if GOOS=windows GOARCH=amd64 CGO_ENABLED=1 CC=x86_64-w64-mingw32-gcc go build -a -buildmode=c-shared -ldflags="-s -w" -o "$OUTPUT_FILE" *.go; then
        echo ""
        echo "✅ Windows DLL编译成功!"
        FILE_SIZE=$(ls -lh "$OUTPUT_FILE" | awk '{print $5}')
        echo "   文件: $OUTPUT_FILE"
        echo "   大小: $FILE_SIZE"
    else
        echo ""
        echo "❌ Windows DLL编译失败"
        exit 1
    fi
    
else
    # 无法编译
    echo "⚠️  当前系统($CURRENT_OS)无法交叉编译Windows DLL"
    echo ""
    echo "解决方案："
    echo "  1. 在Windows系统上运行此脚本"
    echo "  2. 安装MinGW交叉编译工具链:"
    echo "     macOS: brew install mingw-w64"
    echo "     Linux: sudo apt-get install mingw-w64"
    echo "  3. 使用Docker容器编译:"
    echo "     docker run --rm -v \$(pwd):/work -w /work golang:latest \\"
    echo "       bash -c 'apt-get update && apt-get install -y mingw-w64 && \\"
    echo "       GOOS=windows GOARCH=amd64 CGO_ENABLED=1 CC=x86_64-w64-mingw32-gcc \\"
    echo "       go build -buildmode=c-shared -ldflags=\"-s -w\" -o ../assets/libs/simple_tunnel_windows_amd64.dll *.go'"
    echo ""
    echo "❌ 跳过Go库编译，但将继续Flutter构建（需要手动提供DLL）"
    
    # 检查是否已有编译好的DLL
    if [[ ! -f "$OUTPUT_FILE" ]]; then
        echo ""
        echo "⚠️  警告: 未找到Windows DLL文件，Flutter构建可能会失败"
        echo "   需要的文件: $OUTPUT_FILE"
        echo ""
        read -p "是否继续Flutter构建? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    fi
fi

cd ..

echo ""

# ============================================================
# 步骤 2: Flutter依赖安装
# ============================================================

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "📦 步骤 2/3: 安装Flutter依赖"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

echo "📥 获取Flutter依赖..."
flutter pub get

echo ""
echo "✅ 依赖安装完成"
echo ""

# ============================================================
# 步骤 3: 构建Flutter Windows应用
# ============================================================

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🏗️  步骤 3/3: 构建Flutter Windows应用"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# 检查是否在非Windows系统上
if [[ "$CURRENT_OS" == "Darwin" ]] || [[ "$CURRENT_OS" == "Linux" ]]; then
    echo "⚠️  Flutter不支持在$CURRENT_OS上交叉编译Windows应用"
    echo ""
    echo "✅ Go Tunnel DLL已成功编译完成！"
    echo "   文件位置: $(pwd)/assets/libs/simple_tunnel_windows_amd64.dll"
    echo ""
    echo "📋 在Windows系统上完成构建的步骤："
    echo ""
    echo "   1. 将整个项目目录复制到Windows机器"
    echo "   2. 确保Windows机器已安装："
    echo "      - Flutter SDK (https://flutter.dev/docs/get-started/install/windows)"
    echo "      - Visual Studio 2022 (带C++桌面开发工作负载)"
    echo "   3. 在Windows命令提示符中运行："
    echo "      cd client"
    echo "      flutter pub get"
    echo "      flutter build windows --release"
    echo ""
    echo "   或者，在Windows上运行此脚本："
    echo "      .\\build_windows_amd64.sh"
    echo ""
    echo "💡 提示: 如果您有Windows虚拟机或远程Windows服务器，"
    echo "   只需要复制整个client目录即可，DLL已经准备好了！"
    echo ""
    
    # 跳过Flutter构建
    exit 0
fi

echo "🔨 开始构建Windows Release版本..."
echo ""

# 清理之前的构建
if [[ -d "build/windows" ]]; then
    echo "🗑️  清理旧的构建文件..."
    rm -rf build/windows
fi

# 构建Windows应用
if flutter build windows --release; then
    echo ""
    echo "✅ Flutter Windows应用构建成功!"
    echo ""
    
    # 显示输出目录
    BUILD_OUTPUT="build/windows/x64/runner/Release"
    if [[ -d "$BUILD_OUTPUT" ]]; then
        echo "📁 构建输出目录:"
        echo "   $SCRIPT_DIR/$BUILD_OUTPUT"
        echo ""
        
        # 显示可执行文件
        if [[ -f "$BUILD_OUTPUT/internal_net_bridge.exe" ]]; then
            FILE_SIZE=$(ls -lh "$BUILD_OUTPUT/internal_net_bridge.exe" | awk '{print $5}')
            echo "🚀 可执行文件:"
            echo "   internal_net_bridge.exe ($FILE_SIZE)"
            echo ""
        fi
        
        # 检查DLL是否被复制
        if [[ -f "$BUILD_OUTPUT/data/flutter_assets/assets/libs/simple_tunnel_windows_amd64.dll" ]]; then
            echo "✅ Go Tunnel DLL已包含在应用中"
        else
            echo "⚠️  警告: Go Tunnel DLL未找到，应用可能无法正常工作"
        fi
        echo ""
        
        # 列出主要文件
        echo "📦 主要文件列表:"
        ls -lh "$BUILD_OUTPUT" | grep -v "^d" | awk '{printf "   %-40s %s\n", $9, $5}'
        echo ""
    fi
    
else
    echo ""
    echo "❌ Flutter Windows应用构建失败"
    exit 1
fi

# ============================================================
# 构建完成总结
# ============================================================

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🎉 Windows AMD64 客户端构建完成!"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "📍 输出位置:"
echo "   $SCRIPT_DIR/$BUILD_OUTPUT"
echo ""
echo "📦 打包建议:"
echo "   1. 将整个Release目录打包为ZIP文件"
echo "   2. 或使用NSIS/Inno Setup创建安装程序"
echo ""
echo "🚀 测试方法:"
echo "   在Windows系统上运行:"
echo "   cd $BUILD_OUTPUT"
echo "   ./internal_net_bridge.exe"
echo ""
echo "⚠️  注意事项:"
echo "   1. 确保目标Windows系统已安装Visual C++ Redistributable"
echo "   2. 首次运行可能需要管理员权限"
echo "   3. 防火墙可能会弹出提示，需要允许网络访问"
echo ""
echo "✨ 完成！"

